package model;

import com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author Lucas Amaral
 */
public class SalasModel {
    private Map<Integer, Sala> salas =  new LinkedHashMap<>();
    private Connection c;
    private Statement st;
    
    public SalasModel(Connection c) {
        this.c = c;        
        try {
            st = (Statement) c.createStatement();
        } catch (SQLException ex) {
            Logger.getLogger(SalasModel.class.getName()).log(Level.SEVERE, null, ex);
        }
        getSelecionaSalas();
    }    

    public Map<Integer, Sala> getSalas() {
        return salas;
    }
    
    public void getSelecionaSalas() {
        String query;
        try {
            query = "select id, numero, capacidade from SALA order by 2;";
            ResultSet rs = st.executeQuery(query);
            if (rs != null) {
                while (rs.next()) {
                    Sala sala = new Sala();
                    sala.setId(rs.getInt("id"));
                    sala.setCapacidade(rs.getInt("capacidade"));
                    sala.setNumero(rs.getInt("numero"));
                    getSalas().put(sala.getId(), sala);
                }
            }
        } catch (Exception e) {/**/}
    }
    
    public void inserirSala(Sala novaSala) {
         try {
             String query = "insert into Sala (numero, capacidade) values ("+ novaSala.getNumero() + ", " + novaSala.getCapacidade() + ")";
             st.executeUpdate(query);
             getSalas().put(novaSala.getId(), novaSala);
         } catch (Exception e) {
             System.out.println(e);
         }
    }
    
    public void excluirSala(Sala salaRemover) {
        try {
            String query = "delete from Sala where id=" + salaRemover.getId();
            st.executeUpdate(query);
            getSalas().remove(salaRemover.getId());
        } catch (Exception e) {
            System.out.println(e);
        }
    }
    
    public void alterarSala(Sala sala) {
        try {
            String query = "update Sala set numero= '" + sala.getNumero() + "', " + "capacidade='" + sala.getCapacidade() + "' where id=" + sala.getId();
            st.executeUpdate(query);
        } catch (Exception e) {}
    }
    
}
